import {Button, Col, message, Modal, Pagination, Row, Select, Space, Table, Tag, Card, Typography, Form} from "antd";
import {useEffect, useState} from "react";
import request from "umi-request";
import {SearchOutlined, ReloadOutlined} from "@ant-design/icons";

const { Title } = Typography;
import TextArea from "antd/lib/input/TextArea";

interface JobLog {
    Id: number;
    TaskId: number;
    TaskName: string;
    ExecutorName: string;
    ExecutorAddress: string;
    StartTime: string;
    EndTime: string;
    ScheduleResult: string;
    Result: string;
    Status: number;
}

interface Response {
    Total: number;
    Data: JobLog[];
    Error: string;
}

interface TaskSelect {
    Id: string;
    TaskName: string;
}

const JobLogsPage = () => {
    const columns = [
        {
            title: "序号",
            dataIndex: "Id",
            key: "Id",
        },
        {
            title: "任务Id",
            dataIndex: "TaskId",
            key: "TaskId",
        },
        {
            title: "任务名称",
            dataIndex: "TaskName",
            key: "TaskName",
        },
        {
            title: "执行器名称",
            dataIndex: "ExecutorName",
            key: "ExecutorName",
        },
        {
            title: "执行器地址",
            dataIndex: "ExecutorAddress",
            key: "ExecutorAddress",
        },
        {
            title: "执行开始时间",
            dataIndex: "StartTime",
            key: "StartTime",
        },
        {
            title: "执行结束时间",
            dataIndex: "EndTime",
            key: "EndTime",
        },
        {
            title: "调度结果",
            dataIndex: "ScheduleResult",
            key: "ScheduleResult",
        },
        {
            title: "执行结果",
            dataIndex: "Result",
            key: "Result",
        },
        {
            title: "任务状态",
            dataIndex: "Status",
            key: "Status",
            render: (status: number) => {
                if (status == 0) {
                    return <Tag>初始化</Tag>;
                } else if (status == 1) {
                    return <Tag color="#87d068">调度成功</Tag>;
                } else if (status == 2) {
                    return <Tag>调度失败</Tag>;
                } else if (status == 3) {
                    return <Tag>执行成功</Tag>;
                } else if (status == 4) {
                    return <Tag>执行失败</Tag>;
                }
            },
        },
        {
            title: "触发类型",
            dataIndex: "TriggerType",
            key: "TriggerType",
            render: (status: number) => {
                if (status == 0) {
                    return <Tag>自动触发</Tag>;
                } else {
                    return <Tag>手动执行</Tag>;
                }
            },
        },
        {
            title: "任务参数",
            dataIndex: "TaskParam",
            key: "TaskParam",
        },
        {
            title: "操作",
            key: "action",
            render: (_: any, record: any) => (
                <Space size="middle">
                    <Button
                        type="primary"
                        onClick={(e) => {
                            queryLogHandler(record.Id);
                        }}
                    >
                        查询客户端执行日志
                    </Button>
                </Space>
            ),
        },
    ];
    const [log, setLog] = useState("");

    const queryLogHandler = (id: number) => {
        request
            .post("/api/client/queryLocalLog", {
                data: {Id: id},
            })
            .then((res) => {
                setLog(res);
                setVisible(true);
            })
            .catch((error) => {
                message.error("请求数据错误！").then((r) => {
                    console.log(r);
                });
            });
    };

    const [selectValue, setSelectValue] = useState("");

    const [tasks, setTasks] = useState<TaskSelect[]>([]);

    const [jobLogs, setJobLogs] = useState<JobLog[]>([]);

    const [taskId, setTaskId] = useState<string>("");

    const [pageNo, setPageNo] = useState<number>(1);

    const [pageSize, setPageSize] = useState<number>(10);

    const [total, setTotal] = useState<number>(0);

    const pageChangeHandler = (n: number, size: number) => {
        setPageNo(n);
        setPageSize(size);
    };

    const onTasksChange = (value: any, option: any) => {
        if (!value) {
            return;
        }
        setSelectValue(value);
    };

    const queryTasks = () => {
        request
            .post("/api/task/select")
            .then((res) => {
                setTasks(res.Data);
            })
            .catch((error) => {
                message.error("请求数据错误！").then((r) => {
                    console.log(r);
                });
            });
    };

    const queryData = () => {
        request
            .post("/api/log/list", {
                data: {taskId: taskId, pageNo: pageNo, pageSize: pageSize},
            })
            .then((res) => {
                setJobLogs(res.Data);
                setTotal(res.Total);
            })
            .catch((error) => {
                message.error("请求数据错误！").then((r) => {
                    console.log(r);
                });
            });
    };
    const [visible, setVisible] = useState(false);

    useEffect(() => {
        queryTasks();
        queryData();
    }, [taskId, pageNo, pageSize]);
    return (
        <div>
            <Card 
                title={<Title level={4}>调度日志管理</Title>}
                style={{ marginBottom: '24px', borderRadius: '8px' }}
            >
                <Form layout="inline" style={{ marginBottom: '24px' }}>
                    <Form.Item>
                        <Select
                            placeholder="请选择任务名称"
                            allowClear
                            options={tasks}
                            style={{width: 240}}
                            fieldNames={{
                                label: "TaskName",
                                value: "Id",
                            }}
                            onChange={onTasksChange}
                            value={selectValue}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button
                            type="primary"
                            icon={<SearchOutlined/>}
                            onClick={() => {
                                setTaskId(selectValue);
                                setPageNo(1);
                                queryData();
                            }}
                        >
                            搜索
                        </Button>
                    </Form.Item>
                    <Form.Item>
                        <Button
                            icon={<ReloadOutlined/>}
                            onClick={() => {
                                setSelectValue("");
                                setTaskId("");
                                setPageNo(1);
                                queryData();
                            }}
                        >
                            重置
                        </Button>
                    </Form.Item>
                </Form>
                
                <Table
                    dataSource={jobLogs}
                    columns={columns}
                    rowKey="Id"
                    pagination={false}
                    bordered
                    size="middle"
                    style={{ marginBottom: '16px' }}
                />
                
                <Pagination
                    showQuickJumper
                    hideOnSinglePage={false}
                    total={total}
                    current={pageNo}
                    pageSize={pageSize}
                    onChange={pageChangeHandler}
                    showSizeChanger
                    showTotal={(total) => `共 ${total} 条记录`}
                    style={{ textAlign: 'right' }}
                />
            </Card>
            <Modal
                title="客户端执行日志"
                centered
                visible={visible}
                onOk={() => {
                    setVisible(false);
                    setLog("");
                }}
                onCancel={() => {
                    setVisible(false);
                    setLog("");
                }}
                width={1000}
            >
                <TextArea rows={10} bordered value={log} readOnly showCount/>
            </Modal>
        </div>
    );
};

export default JobLogsPage;
